<template>
	<view>
		<!-- 会员统计 -->
		<view class="stat-cards">
			<!-- 卡片内容省略 -->
		</view>

		<!-- 搜索和操作按钮区域 -->
		<view class="controls">
			<!-- 搜索框 -->
			<uni-search-bar @confirm="search" v-model="searchQuery" class="search-bar" />

			<!-- 操作按钮 -->
			<view class="control-buttons">
				<button class="control-button" size="mini" @click="fetchMembers">查询</button>
				<!-- <button class="control-button" size="mini" @click="openAddPopup">新增会员</button>
		-->
				<!-- 导入导出按钮 -->

				<button class="control-button" @click="importMembers" size="mini">批量导入</button>
				<button class="control-button" @click="exportMembers" size="mini">会员列表导出</button>
				<!-- 隐藏的文件输入，用于文件上传 -->
				<input type="file" ref="fileInput" @change="handleFileUpload" style="display: none;" />
			</view>
		</view>

		<!-- 店铺分段器 -->
		<view style="background-color:#fff;padding: 20px;">
			<uni-segmented-control :current="currentStoreIndex" :values="storeOptions" @clickItem="selectStore"
				activeColor="#4cd964" />
		</view>

		<!-- 会员列表表格 -->
		<view v-if="!showMemberDetails">
			<uni-table>
				<uni-tr>
					<uni-th align="center">生日</uni-th>
					<uni-th align="center">卡号</uni-th>
					<uni-th align="center">姓名</uni-th>
					<uni-th align="center">性别</uni-th>
					<uni-th align="center">电话</uni-th>
					<uni-th align="center">分店</uni-th>
					<uni-th align="center">余额</uni-th>
					<uni-th align="center">等级</uni-th>
					<uni-th align="center">积分</uni-th>
					<uni-th align="center">操作</uni-th>
				</uni-tr>

				<!-- 动态生成数据行 -->
				<uni-tr v-for="(member, index) in filteredMembers" :key="index">
					<uni-td align="center">{{ member.birth_date }}</uni-td>
					<uni-td align="center">{{ member.card_number }}</uni-td>
					<uni-td align="center">{{ member.name }}</uni-td>
					<uni-td align="center" v-if="member.gender === 'secret'">保密</uni-td>
					<uni-td align="center" v-else-if="member.gender === 'male'">男</uni-td>
					<uni-td align="center" v-else>女</uni-td>
					
					<uni-td align="center">{{ member.phone }}</uni-td>
					<uni-td align="center">{{ member.store_name }}</uni-td>
					<uni-td align="center">{{ member.account_balance }}</uni-td>
					<uni-td align="center">{{ member.level_name }}</uni-td>
					<uni-td align="center">{{ member.integral }}</uni-td>

					<uni-td align="center">
						<button class="button" type="warn" @click="confirmDelete(member.id, index)" size="mini"
							style="margin-left: 5px;">删除</button>
						<button @click="openDetails(member.id)" size="mini" style="margin-left: 5px;">查看详情</button>
					</uni-td>
				</uni-tr>
			</uni-table>

			<!-- 分页组件 -->
			<view style="margin-top: 20px;">
				<uni-pagination :total="totalPages * pageSize" :page-size="pageSize" :current="currentPage"
					@change="handlePageChange" />
			</view>
		</view>

		<!-- 会员详情组件 -->
		<member-details v-else :member-id="selectedMemberId" @close="closeDetails" />

		<!-- 使用 uni-popup 的弹窗 -->
		<uni-popup ref="editPopup" type="center">
			<view class="member-modal">
				<h3>编辑会员信息</h3>
				<!-- 表单输入字段 -->
				<view class="form-row">
					<label>姓名：</label>
					<input v-model="currentMember.name" class="input-field" />
				</view>
				<view class="form-row">
					<label>卡号：</label>
					<input v-model="currentMember.cardNumber" class="input-field" />
				</view>
				<view class="form-row">
					<label>电话：</label>
					<input v-model="currentMember.phone" class="input-field" />
				</view>
				<view class="form-row">
					<label>分店：</label>
					<input v-model="currentMember.store_name" class="input-field" />
				</view>
				<view class="form-row">
					<label>余额：</label>
					<input v-model="currentMember.balance" class="input-field" />
				</view>
				<view class="form-row">
					<label>等级：</label>
					<input v-model="currentMember.level" class="input-field" />
				</view>
				<view class="form-row">
					<label>会员状态：</label>
					<input v-model="currentMember.status" class="input-field" />
				</view>
				<view class="form-row">
					<label>操作员：</label>
					<input v-model="currentMember.operator" class="input-field" />
				</view>
				<!-- 保存和取消按钮 -->
				<view class="button-group">
					<button class="modal-button save" @click="saveMember" size="mini">保存</button>
					<button class="modal-button cancel" @click="closePopup" size="mini">取消</button>
				</view>
			</view>
		</uni-popup>

		<!-- 新增会员弹窗 -->
		<uni-popup ref="addPopup" type="center">
			<view class="member-modal">
				<h3>新增会员</h3>
				<!-- 表单输入字段 -->
				<view class="form-row">
					<label>姓名：</label>
					<input v-model="newMember.name" class="input-field" />
				</view>
				<view class="form-row">
					<label>卡号：</label>
					<input v-model="newMember.cardNumber" class="input-field" />
				</view>
				<view class="form-row">
					<label>电话：</label>
					<input v-model="newMember.phone" class="input-field" />
				</view>
				<view class="form-row">
					<label>分店：</label>
					<input v-model="newMember.store_name" class="input-field" />
				</view>
				<view class="form-row">
					<label>余额：</label>
					<input v-model="newMember.balance" class="input-field" />
				</view>
				<view class="form-row">
					<label>等级：</label>
					<input v-model="newMember.level" class="input-field" />
				</view>
				<view class="form-row">
					<label>会员状态：</label>
					<input v-model="newMember.status" class="input-field" />
				</view>
				<view class="form-row">
					<label>操作员：</label>
					<input v-model="newMember.operator" class="input-field" />
				</view>
				<!-- 保存和取消按钮 -->
				<view class="button-group">
					<button class="modal-button save" @click="addMember" size="mini">保存</button>
					<button class="modal-button cancel" @click="closePopup" size="mini">取消</button>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import MemberDetails from '@/pages/memberList/member_details.vue';

	export default {
		components: {
			MemberDetails,
		},
		data() {
			return {
				members: [],
				filteredMembers: [],
				userInfo: {}, // 登录信息
				currentMember: {},
				newMember: {
					name: '',
					cardNumber: '',
					phone: '',
					store_name: '',
					balance: '',
					level: '',
					status: '',
					operator: ''
				},
				totalPages: 1,
				pageSize: 10,
				currentPage: 1,
				searchQuery: '',
				currentStoreIndex: 0,
				storeOptions: [],
				store_id: [],
				showMemberDetails: false,
				selectedMemberId: null,
			};
		},
		methods: {
			importMembers() {
				this.chooseFile();
			},
			// 选择文件
			chooseFile() {
				uni.chooseFile({
					count: 1,
					success: (res) => {
						const file = res.tempFiles[0];
						this.uploadFile(file);
					},
					fail: (err) => {
						uni.showToast({
							title: '选择文件失败',
							icon: 'none',
							duration: 2000
						});
					}
				});
			},
			// 上传文件
			uploadFile(file) {
				uni.uploadFile({
					url: 'https://erp.kzjpht.com/index/uploader/upload_file', // 后端文件上传接口地址
					filePath: file.path,
					name: 'file',
					formData: {
						user_id: this.userInfo.user_id
					},
					success: (uploadFileRes) => {
						const res = JSON.parse(uploadFileRes.data);
						if (res.code === 200) {
							console.log(res);
							this.importMemberFile(res.data); // 调用会员导入接口，传递文件路径
						} else {
							uni.showToast({
								title: res.message,
								icon: 'none',
								duration: 2000
							});
						}
					},
					fail: (err) => {
						uni.showToast({
							title: '上传文件失败',
							icon: 'none',
							duration: 2000
						});
					}
				});
			},
			// 导入会员信息
			importMemberFile(filePath) {
				this.$myRuquest({
					url: '/index/plugin.users/import_members',
					method: 'POST',
					data: {
						file_path: filePath,
						user_id: this.userInfo.user_id
					}
				}).then((res) => {
					if (res.data.code === 200) {
						uni.showToast({
							title: '导入成功',
							icon: 'success',
							duration: 2000
						});
						// 重新加载会员列表
						this.fetchMembers();
					} else {
						uni.showToast({
							title: res.data.message,
							icon: 'none',
							duration: 2000
						});
					}
				}).catch((error) => {
					uni.showToast({
						title: '导入失败',
						icon: 'none',
						duration: 2000
					});
				});
			},
			fetchMembers() {
				// 重新加载会员列表的逻辑
			},

			async fetchMembers() {
				const res = await this.$myRuquest({
					url: '/index/plugin.users/get_members',
					method: 'GET',
					data: {
						page: this.currentPage,
						pageSize: this.pageSize,
						searchQuery: this.searchQuery,
						user_id: this.userInfo.user_id,
						shop_id: this.store_id[this.currentStoreIndex] === '所有店铺' ? '' : this.store_id[this
							.currentStoreIndex]
					}
				});
				if (res.data.code === 200) {
					this.members = res.data.data.members;
					this.filteredMembers = [...this.members];
					this.totalPages = res.data.data.totalPages;
				} else {
					uni.showToast({
						title: res.data.message,
						duration: 2000,
						icon: 'none'
					});
				}
			},
			exportMembers() {
				console.log(this.userInfo.user_id);
				// 导出会员信息的逻辑
				window.open(`https://erp.kzjpht.com/index/plugin.users/export_members?user_id=${this.userInfo.user_id}`,
					'_blank');
			},

			async fetchStores() {
				const res = await this.$myRuquest({
					url: '/index/plugin.users/getStores',
					method: 'GET',
					data: {
						user_id: this.userInfo.user_id
					}
				});
				if (res.data.code === 200) {
					this.storeOptions = ['所有店铺', ...res.data.data.map(store => store.name)];
					this.store_id = ['', ...res.data.data.map(store => store.id)];
				} else {
					uni.showToast({
						title: res.data.message,
						duration: 2000,
						icon: 'none'
					});
				}
			},
			search() {
				this.currentPage = 1;
				this.fetchMembers();
			},
			selectStore(e) {
				this.currentStoreIndex = e.currentIndex;
				this.currentPage = 1;
				this.fetchMembers();
			},
			openAddPopup() {
				this.newMember = {
					name: '',
					cardNumber: '',
					phone: '',
					store_name: '',
					balance: '',
					level: '',
					status: '',
					operator: ''
				};
				this.$refs.addPopup.open();
			},
			closePopup() {
				this.$refs.editPopup.close();
				this.$refs.addPopup.close();
			},
			saveMember() {
				const index = this.members.findIndex(m => m.cardNumber === this.currentMember.cardNumber);
				if (index !== -1) {
					this.members.splice(index, 1, {
						...this.currentMember
					});
					this.filteredMembers = [...this.members];
				}
				this.closePopup();
			},
			addMember() {
				const newId = this.members.length + 1;
				const newMember = {
					id: newId,
					...this.newMember,
					date: new Date().toISOString().split('T')[0]
				};
				this.members.push(newMember);
				this.filteredMembers = [...this.members];
				this.closePopup();
			},
			async confirmDelete(memberId, index) {
				if (confirm('确认删除该会员信息吗？')) {
					const res = await this.$myRuquest({
						url: '/index/plugin.users/delete_member',
						method: 'POST',
						data: {
							id: memberId
						}
					});
					if (res.data.code === 200) {
						uni.showToast({
							title: '删除成功',
							icon: 'success',
							duration: 2000
						});
						this.members.splice(index, 1);
						this.filteredMembers = [...this.members];
					} else {
						uni.showToast({
							title: res.data.message,
							duration: 2000,
							icon: 'none'
						});
					}
				}
			},
			handlePageChange(e) {
				this.currentPage = e.current;
				this.fetchMembers();
			},
			openDetails(memberId) {
				this.selectedMemberId = memberId;
				this.showMemberDetails = true;
			},
			closeDetails() {
				this.showMemberDetails = false;
				this.selectedMemberId = null;
			},
			//检查是否登录
			checkLoginStatus() {
				const token = uni.getStorageSync('token');
				if (token) {
					this.userInfo = JSON.parse(uni.getStorageSync('userInfo'));
				} else {
					this.userInfo = {};
					this.$router.push('/pages/login/login');
				}
			}
		},
		created() {
			this.checkLoginStatus();
			this.fetchMembers();
			this.fetchStores();
		}
	};
</script>

<style>
	.member-modal {
		width: 80%;
		max-width: 500px;
		padding: 20px;
		background-color: #fff;
		border-radius: 8px;
		box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
	}

	h3 {
		margin-bottom: 20px;
		text-align: center;
		color: #333;
	}

	.form-row {
		display: flex;
		align-items: center;
		margin-bottom: 15px;
	}

	label {
		width: 80px;
		color: #666;
		margin-right: 10px;
	}

	.input-field {
		flex: 1;
		padding: 8px;
		border: 1px solid #ddd;
		border-radius: 4px;
		outline: none;
	}

	.button-group {
		display: flex;
		justify-content: space-between;
		margin-top: 20px;
	}

	.modal-button {
		flex: 1;
		padding: 10px 15px;
		margin: 0 5px;
		background-color: #1abc9c;
		color: #fff;
		border: none;
		border-radius: 4px;
		cursor: pointer;
	}

	.modal-button.save:hover {
		background-color: #16a085;
	}

	.modal-button.cancel {
		background-color: #e74c3c;
	}

	.modal-button.cancel:hover {
		background-color: #c0392b;
	}

	.stat-cards {
		display: flex;
		flex-wrap: wrap;
		gap: 10px;
		margin-bottom: 20px;
	}

	.stat-card {
		flex: 1 1 23%;
		display: flex;
		justify-content: space-between;
		align-items: center;
		background-color: #f5f5f5;
		padding: 10px;
		border-radius: 8px;
		box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
		border: 1px solid #ddd;
	}

	.card-section {
		display: flex;
		flex-direction: column;
		align-items: center;
		flex: 1;
		text-align: center;
	}

	.divider {
		width: 2px;
		height: 40px;
		background-color: #dcdcdc;
	}

	.green {
		background-color: #2ecc71;
		color: #fff;
	}

	.blue {
		background-color: #3498db;
		color: #fff;
	}

	.orange {
		background-color: #f39c12;
		color: #fff;
	}

	.red {
		background-color: #e74c3c;
		color: #fff;
	}

	.stat-card text {
		margin-top: 5px;
	}

	.controls {
		display: flex;
		align-items: center;
		flex-wrap: wrap;
		padding: 20px;

		background: #fff;
	}

	.search-bar {
		flex: 1;
		margin-right: 15px;
	}

	.control-buttons {
		display: flex;
		flex-wrap: wrap;
		gap: 10px;
	}

	.control-button {
		padding: 8px 12px;
		background-color: #3498db;
		color: #fff;
		border: none;
		border-radius: 4px;
		cursor: pointer;
	}

	.control-button:hover {
		background-color: #2980b9;
	}
</style>